<template>
	<view class="uni-list list-pd">
		<view class="uni-list-cell cell-pd">
			<view class="uni-uploader">
				<view class="uni-uploader-head">
					<view class="uni-uploader-title">点击可预览选好的图片</view>
					<view class="uni-uploader-info">{{ imageList.length }}/9</view>
				</view>
				<view class="uni-uploader-body">
					<view class="uni-uploader__files">
						<block v-for="(image, index) in imageList" :key="index">
							<view class="uni-uploader__file">
								<image class="uni-uploader__img" :src="image" :data-src="image" @tap="previewImage"></image>
								<view class="remove_icon iconfont icon-delete" @click="deletePics(index)"></view>
							</view>
						</block>
						<view class="uni-uploader__input-box"><view class="uni-uploader__input" @tap="chooseImage"></view></view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	var sourceType = [['camera'], ['album'], ['camera', 'album']];
	var sizeType = [['compressed'], ['original'], ['compressed', 'original']];
	export default {
		data() {
			return {
				// 存储上传的图片
				title: 'choose/previewImage',
				imageList: [],
				sourceTypeIndex: 2,
				sourceType: ['拍照', '相册', '拍照或相册'],
				sizeTypeIndex: 2,
				sizeType: ['压缩', '原图', '压缩或原图'],
				countIndex: 8,
				count: [1, 2, 3, 4, 5, 6, 7, 8, 9]
			}
		},
		methods: {
			chooseImage: async function() {
				// #ifdef APP-PLUS
				// TODO 选择相机或相册时 需要弹出actionsheet，目前无法获得是相机还是相册，在失败回调中处理
				if (this.sourceTypeIndex !== 2) {
					let status = await this.checkPermission();
					if (status !== 1) {
						return;
					}
				}
				// #endif
			
				if (this.imageList.length === 9) {
					return;
				}
				uni.chooseImage({
					sourceType: sourceType[this.sourceTypeIndex],
					sizeType: sizeType[this.sizeTypeIndex],
					count: this.imageList.length + this.count[this.countIndex] > 9 ? 9 - this.imageList.length : this.count[this.countIndex],
					success: res => {
						this.imageList = this.imageList.concat(res.tempFilePaths);
						this.$emit('upload',this.imageList)
					}
				});
			},
			// 预览图片
			previewImage: function(e) {
				var current = e.target.dataset.src;
				uni.previewImage({
					current: current,
					urls: this.imageList
				});
			},
			// 删除图片
			deletePics(index) {
				uni.showModal({
					title: '提示',
					content: '是否要删除这张图片',
					success: (res)=> {
						if (res.confirm) {
							this.$emit('remove',index)
						} else if (res.cancel) {
							console.log('用户点击取消');
						}
					}
				});
			}
		}
	}
</script>

<style lang="less" scoped>
.cell-pd {
	padding: 22rpx 30rpx;
}

.list-pd {
	margin-top: 50rpx;
	.uni-uploader__file {
		position: relative;
	}
	.remove_icon {
		position: absolute;
		right: -15rpx;
		top: -15rpx;
		height: 35rpx;
		width: 35rpx;
		border: 2rpx solid #000;
		display: flex;
		justify-content: center;
		align-items: center;
		border-radius: 50%;
		background-color: red;
	}
}
</style>
